let ErrorUtils = require('../utils/error/ErrorUtils');
let {FormId,Order} = require('../models');
const {infoLogger, errorLogger} = require('../config').logger;
const Joi = require('joi');
const moment = require('moment');
let rp = require('request-promise');
const config=require('../config');
let WechatService = require("../service/wechat");

class FormIdService {

    /**
     * 创建表单
     * @returns {Promise<void>}
     */
    static async create(data,userInfo) {
        infoLogger.info(">>>>>form表单创建开始,请求参数",data);
        await FormIdService.checkFormIdData(data);
        data.userId = userInfo._id;
        data.openId = userInfo.openId;
        data.isUsed=false;
        infoLogger.info(">>>>>form表单创建结束");
        return await FormId.create(data);
    }

    /**
     * 预约发送模版消息
     * @param data
     * @returns {Promise<void>}
     */
    static async sendCourseOrderMsg(data) {
        infoLogger.info(">>>>>发送预约消息,请求参数",data);
        let token=data.token;
        let info = {
            touser: data.openId,
            template_id:config.wechatTemplate.courseOrder,
            form_id: data.formId,
            color: '#ff0000',
            data: {
                keyword1: {
                    value: data.username,
                    color: '#173177',
                },
                keyword2: {
                    value: data.phone,
                    color: '#173177',
                },
                keyword3: {
                    value: data.address,
                    color: '#173177',
                },
                keyword4: {
                    value: data.orderTime,
                    color: '#173177',
                }
            },
            //emphasis_keyword: "keyword4.DATA",
            page: 'pages/myAppoint/main?type=1'
        };
        let url = `https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=${token}`;
        let result = await rp({
            uri: url,
            method: 'POST',
            json: true,
            body: info
        });
        infoLogger.info(">>>>>发送预约消息结束");
        if (result.errcode == 0) {
            infoLogger.info(">>>>预约模版消息发送给用户",data.openId,"成功",result);
            //await this.updateActiveReceiveCode(msg.receiveId);
        } else {
            infoLogger.info(">>>>预约模版消息发送给用户",data.openId,"失败",result);
        }
    }
    /**
     * 预约发送模版消息
     * @param data
     * @returns {Promise<void>}
     */
    static async findCourseEnd() {
        infoLogger.info(">>>>数据查询开始");
        let orderData=await Order.find()
            .where('isSend',false)
            .where('orderTime')
            .gte(new Date())
            .exec();
        infoLogger.info(">>>>数据长度",orderData.length);
        if(orderData){
            for(let i=0;i<orderData.length;i++){
                let info={};
                let orderTime = moment(orderData[i].orderTime).format('YYYY年MM月DD日');
                let orderTime1 = moment(orderData[i].orderTime).format('YYYY.MM.DD');
                let formIdData=await FormId.findOne().sort({_id:-1}).lean().exec();
                infoLogger.info(">>>>formid数据",formIdData);
                let formId=''
                if(formIdData){
                    formId=formIdData.formId;
                    info.formId=formId;
                }
                if(!formId){
                    continue;
                }else{
                    info.orderTime=orderTime;
                    info.orderTime1=orderTime1;
                    info.openId=orderData[i].openId;
                    info.orderType=orderData[i].orderType?orderData[i].orderType:'基础滑行';
                    info.teacher=orderData[i].teacher;
                    info.address=orderData[i].address;
                    await FormIdService.sendCourseEndMsg(info);
                    orderData[i].isSend=true;
                    await orderData[i].save();
                    FormId.remove(formIdData._id);
                }
            }
        }
    }
    static async sendCourseEndMsg(data){
        infoLogger.info(">>>>结束模版消息发送开始,参数",data);
        let token=await WechatService.getAccessToken();
        let info = {
            touser: data.openId,
            template_id:config.wechatTemplate.courseEnd,
            form_id: data.formId,
            color: '#ff0000',
            data: {
                keyword1: {
                    value: data.orderType,
                    color: '#173177',
                },
                keyword2: {
                    value: data.orderTime,
                    color: '#173177',
                },
                keyword3: {
                    value: data.orderTime1,
                    color: '#173177',
                },
                keyword4: {
                    value: data.teacher,
                    color: '#173177',
                },
                keyword5: {
                    value: data.address,
                    color: '#173177',
                }
            },
            //emphasis_keyword: "keyword4.DATA",
            page: 'pages/myAppoint/main?type=2'
        };
        let url = `https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=${token}`;
        let result = await rp({
            uri: url,
            method: 'POST',
            json: true,
            body: info
        });
        if (result.errcode == 0) {
            infoLogger.info(">>>>结束模版消息发送给用户",data.openId,"成功",result);
            //await this.updateActiveReceiveCode(msg.receiveId);
            return true;
        } else {
            infoLogger.info(">>>>结束模版消息发送给用户",data.openId,"失败",result);
            return false;
        }
    }
    /**
     * 核验表单信息
     * @param data
     * @returns {*}
     */
    static checkFormIdData(data) {
        let schema = Joi.object({
            formId: Joi.string().min(2).max(40).required(),
        });
        let result = Joi.validate(data, schema);
        return result;
    }

    /**
     * 核验订单信息
     * @param data
     * @returns {*}
     */
    static checkOrderData(data) {
        let schema = Joi.object({
            username: Joi.string().min(2).max(20).required(),
            phone: Joi.string().min(2).max(20).required(),
            address: Joi.string().min(2).max(40).required(),
            orderTime: Joi.string().min(2).max(20).required(),
            formId: Joi.string().min(2).max(40).required(),
        });
        let result = Joi.validate(data, schema);
        return result;
    }
}

module.exports = FormIdService;
